from PyQt6.QtWidgets import QDialog, QFormLayout, QLineEdit, QComboBox, QDialogButtonBox, QVBoxLayout, QGroupBox, QGridLayout, QLabel, QCheckBox
from PyQt6.QtGui import QIntValidator
from utils.crypto import encrypt

class ConnectionDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("新建数据库连接")
        self.resize(500, 400)

        layout = QVBoxLayout(self)

        # 连接基本信息
        basic_group = QGroupBox("连接设置")
        basic_layout = QFormLayout(basic_group)

        self.conn_name = QLineEdit()
        self.conn_name.setPlaceholderText("连接名称")
        basic_layout.addRow("连接名称:", self.conn_name)

        self.conn_type = QComboBox()
        self.conn_type.addItems(["MySQL", "PostgreSQL", "SQL Server", "SQLite", "MongoDB"])
        self.conn_type.currentTextChanged.connect(self.update_ui)
        basic_layout.addRow("数据库类型:", self.conn_type)

        self.host = QLineEdit("localhost")
        self.host.setPlaceholderText("主机名或IP地址")
        basic_layout.addRow("主机:", self.host)

        self.port = QLineEdit()
        self.port.setPlaceholderText("端口")
        self.port.setValidator(QIntValidator(1, 65535))
        basic_layout.addRow("端口:", self.port)

        layout.addWidget(basic_group)

        # 认证信息
        auth_group = QGroupBox("认证设置")
        auth_layout = QFormLayout(auth_group)

        self.username = QLineEdit()
        self.username.setPlaceholderText("用户名")
        auth_layout.addRow("用户名:", self.username)

        self.password = QLineEdit()
        self.password.setPlaceholderText("密码")
        self.password.setEchoMode(QLineEdit.EchoMode.Password)
        auth_layout.addRow("密码:", self.password)

        layout.addWidget(auth_group)

        # 数据库特定设置
        self.db_specific_group = QGroupBox("数据库设置")
        self.db_specific_layout = QFormLayout(self.db_specific_group)

        self.database = QLineEdit()
        self.database.setPlaceholderText("数据库名称")
        self.db_specific_layout.addRow("数据库:", self.database)

        self.sqlite_path = QLineEdit()
        self.sqlite_path.setPlaceholderText("SQLite数据库文件路径")
        self.db_specific_layout.addRow("文件路径:", self.sqlite_path)

        layout.addWidget(self.db_specific_group)

        # 高级设置
        advanced_group = QGroupBox("高级设置")
        advanced_layout = QGridLayout(advanced_group)

        self.ssh_tunnel = QCheckBox("使用SSH隧道")
        advanced_layout.addWidget(self.ssh_tunnel, 0, 0)

        self.ssl_connection = QCheckBox("使用SSL连接")
        advanced_layout.addWidget(self.ssl_connection, 0, 1)

        self.save_password = QCheckBox("保存密码")
        self.save_password.setChecked(True)
        advanced_layout.addWidget(self.save_password, 1, 0)

        layout.addWidget(advanced_group)

        # 按钮
        button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)

        # 初始化UI
        self.update_ui()

    def update_ui(self):
        """根据选择的数据库类型更新UI"""
        db_type = self.conn_type.currentText()

        # 设置默认端口
        if db_type == "MySQL":
            self.port.setText("3306")
        elif db_type == "PostgreSQL":
            self.port.setText("5432")
        elif db_type == "SQL Server":
            self.port.setText("1433")
        elif db_type == "MongoDB":
            self.port.setText("27017")
        else:  # SQLite
            self.port.clear()

        # 显示/隐藏特定控件
        if db_type == "SQLite":
            self.host.setEnabled(False)
            self.port.setEnabled(False)
            self.username.setEnabled(False)
            self.password.setEnabled(False)
            self.database.setEnabled(False)
            self.sqlite_path.setEnabled(True)
            self.db_specific_layout.labelForField(self.database).setText("数据库:")
            self.db_specific_layout.labelForField(self.sqlite_path).setText("文件路径:")
        elif db_type == "MongoDB":
            self.host.setEnabled(True)
            self.port.setEnabled(True)
            self.username.setEnabled(True)
            self.password.setEnabled(True)
            self.database.setEnabled(True)
            self.sqlite_path.setEnabled(False)
            self.db_specific_layout.labelForField(self.database).setText("数据库:")
        else:
            self.host.setEnabled(True)
            self.port.setEnabled(True)
            self.username.setEnabled(True)
            self.password.setEnabled(True)
            self.database.setEnabled(True)
            self.sqlite_path.setEnabled(False)
            self.db_specific_layout.labelForField(self.database).setText("数据库:")

    def get_connection_info(self):
        """获取连接信息"""
        conn_type = self.conn_type.currentText()

        info = {
            "name": self.conn_name.text(),
            "type": conn_type,
            "host": self.host.text() if conn_type != "SQLite" else "",
            "port": int(self.port.text()) if self.port.text() and conn_type != "SQLite" else 0,
            "user": self.username.text() if conn_type != "SQLite" else "",
            "password": encrypt(self.password.text()) if self.password.text() and conn_type != "SQLite" else "",
            "database": self.database.text() if conn_type != "SQLite" else "",
            "database_path": self.sqlite_path.text() if conn_type == "SQLite" else "",
            "ssh_tunnel": self.ssh_tunnel.isChecked(),
            "ssl": self.ssl_connection.isChecked(),
            "save_password": self.save_password.isChecked()
        }

        return info